/**
 * Created with  SublimeText
 * @Author:      Lyle
 * @DateTime:    2017-06-29 15:14:47
 * @Description: 
 */

import * as API from '../../api'
import Vue from 'vue'

/* 
errorCode:
    ERROR: 0,
    CONNECTING: 1,
    CONNFAIL: 2,
    AUTHENTICATING: 3,
    AUTHFAIL: 4,
    CONNECTED: 5,
    DISCONNECTED: 6,
    DISCONNECTING: 7,
    ATTACHED: 8,
    REDIRECT: 9,
    CONNTIMEOUT: 10,
    ....
*/
const state = {
    unReadCount: 0,
    unReadList: {},
    contactList: [],
    messageHandlerChatRoomList: [], //通过messageHandler来的群聊记录
    topContactList: [], //连接IM后，最近聊过的人（置顶）
    errorCode: '',
    chattingUserId: ''
}

const mutations = {

    unReadCount(state, data) {
        state.unReadCount = data;
    },

    unreadHandler(state, data) {
        state.unReadCount = data.count;
        state.unReadList = data.messages;
    },

    messageHandler(state, data) {
        if (data.forwarded) {
            if (state.chattingUserId == data.receiverId) {
                let messages = state.unReadList[data.receiverId] || [];
                if (_.isEmpty(messages)) {
                    Vue.set(state.unReadList, data.receiverId, [data]);
                } else {
                    messages.unshift(data);
                }
            } else {
                //add to contact list 
                let index = _.findIndex(state.topContactList, { contactId: data.receiverId });
                if (index > -1) {
                    Vue.delete(state.topContactList, index);
                }
                data.contactId = data.receiverId;
                Vue.set(state.topContactList, state.topContactList.length, data);

                // delete unread number
                let length = state.unReadList[data.receiverId] ? state.unReadList[data.receiverId].length : 0;
                state.unReadCount = state.unReadCount - length;
                Vue.delete(state.unReadList, data.receiverId);

                //delete local history
                delete ArchiveMessageHistory[data.receiverId];
            }

        } else {
            let messages = state.unReadList[data.senderId] || [];
            if (_.isEmpty(messages)) {
                //state.unReadList[data.senderId] = [data];
                Vue.set(state.unReadList, data.senderId, [data]);
            } else {
                messages.unshift(data);
            }
            state.unReadCount++;
        }

    },

    contactHandler(state, data) {
        for (let i in data) {
            state.contactList.push(data[i]);
        }
    },

    sendMessage(state, data) {
        let messages = state.unReadList[data.receiverId] || [];
        if (_.isEmpty(messages)) {
            Vue.set(state.unReadList, data.receiverId, [data]);
            // state.unReadList[data.receiverId] = [data];
        } else {
            messages.unshift(data);
        }
        state.unReadCount++;
    },

    deleteUnread(state, data) {
        if (state.unReadList[data]) {
            let length = state.unReadList[data] ? state.unReadList[data].length : 0;
            state.unReadCount = state.unReadCount - length;
            Vue.delete(state.unReadList, data);
        }
    },

    chatRoomMessageHandle(state, data) {
        /*
        if (state.messageHandlerChatRoomList.length > 100) {
            Vue.delete(state.messageHandlerChatRoomList, 0);
        }
        */
        Vue.set(state.messageHandlerChatRoomList, state.messageHandlerChatRoomList.length, data);
    },
    /*
    chatRoomHandle(state, data) {
        for (let i in data) {
            state.messageHandlerChatRoomList.push(data[i]);
        }
    },
    */

    topContactList(state, data) {
        let index = _.findIndex(state.topContactList, { contactId: data.contactId });
        if (index > -1) {
            // delete state.topContactList[index];
            Vue.delete(state.topContactList, index);
        }
        // state.topContactList.unshift(data)
        Vue.set(state.topContactList, state.topContactList.length, data);
        console.log('topContactList', state.topContactList)
    },

    changeMessageStatus(state, data) {
        let message = _.find(state.unReadList[data.receiverId], { id: data.id });
        Object.assign(message, data);
    },

    messageErrorHandler(state, data) {
        state.errorCode = data;
    },

    sendMessageErrorHandler(state, data) {
        //state.errorCode = data;
    },

    resetChat(state, data) {
        state.unReadCount = 0;
        state.unReadList = {};
        state.contactList = [];
        state.messageHandlerChatRoomList = [];
        state.topContactList = [];
        state.errorCode = '';
    },

    changeChattingUserId(state, data) {
        state.chattingUserId = data;
    },

    deleteContact(state, data) {
        let index = _.findIndex(state.topContactList, { contactId: data });
        if (index > -1) {
            Vue.delete(state.topContactList, index);
        }
        let contactIndex = _.findIndex(state.contactList, { contactId: data });
        if (contactIndex > -1) {
            Vue.delete(state.contactList, contactIndex);
        }
        if (state.unReadList[data]) {
            let length = state.unReadList[data] ? state.unReadList[data].length : 0;
            state.unReadCount = state.unReadCount - length;
            Vue.delete(state.unReadList, data);
        }
    }
}

const actions = {

    chat_unReadCount({ commit, state }, num) {
        commit('unReadCount', num);
    },

    chat_unreadHandler({ commit, state }, obj) {
        let messageObj = obj.args;
        if (messageObj.count > 0) {
            commit('unreadHandler', messageObj);
        }
    },

    chat_messageHandler({ commit, state }, obj) {
        if (obj.args.type == 'chat') {
            commit('messageHandler', obj.args);
        } else if (obj.args.type == 'groupchat') {
            commit('chatRoomMessageHandle', obj.args);
        }
    },

    chat_contactHandler({ commit, state }, obj) {
        commit('contactHandler', obj);
    },
    /*
    chat_chatRoomHandle({ commit, state }, obj) {
        commit('chatRoomHandle', obj);
    },
    */
    chat_sendMessage({ commit, state }, obj) {
        commit('sendMessage', obj);
    },

    chat_deleteUnread({ commit, state }, data) {
        commit('deleteUnread', data);
    },

    chat_topContactList({ commit, state }, obj) {
        commit('topContactList', obj);
    },

    chat_changeMessageStatus({ commit, state }, obj) {
        commit('changeMessageStatus', obj)
    },

    chat_messageErrorCode({ commit, state }, obj) {
        commit('messageErrorHandler', obj);
    },

    chat_reset({ commit, state }) {
        commit('resetChat');
    },

    chat_changeChattingUserId({ commit, state }, usr_id) {
        commit('changeChattingUserId', usr_id)
    },

    chat_deleteContact({ commit, state }, usr_id) {
        commit('deleteContact', usr_id);
    }

}

const getters = {

}

export default {
    state,
    getters,
    actions,
    mutations
}
